<?php


namespace App\Controller\Api\V1;

use App\Common\BeseController;
use App\Model\Mysql\OrderModel;
use App\Model\Mysql\ProjectModel;
use App\Model\Mysql\UserModel;
use App\Service\NumberService;


class Order extends BeseController
{

    public function orderRequire()
    {
        $input = $this->input;

        $info = ProjectModel::getOne(['id' => $input['project_id']], ['id', 'order_require']);

        if (!$info) return $this->responseError('项目不存在');

        return $this->responseSuccess('请求成功', $info);
    }


    public function orderSubmit()
    {
        $input = $this->input;


        $info = ProjectModel::getOne(['id' => $input['project_id']], ['id', 'order_require', 'integral', 'at_level']);

        if (!$info) return $this->responseError('项目不存在');

        $userId = $input['user']['id'] ?? 1;

        $levelId = UserModel::getValue(['id' => $userId], 'level_id');


        if ($info['at_level'] > $levelId) return $this->responseError('你的段位不足，不允许接这个单');

        $data = [
            'project_id' => $input['project_id'],
            'user_id' => $userId,
            'order_sn' => NumberService::order(),
            'order_integral' => $info['integral'],
            'client_name' => $input['client_name'],
            'client_mobile' => $input['client_mobile'],
            'client_realname' => $input['client_realname'],
            'client_address' => $input['client_address'] ?? '',
            'connect_status' => $input['connect_status'] ?? '',
            'detail' => $input['detail'] ?? '',
            'help_content' => $input['help_content'] ?? '',
        ];

        $res = OrderModel::addData($data);

        if (!$res) return $this->responseError('操作失败');

        return $this->responseSuccess('操作成功');
    }


    public function orderList()
    {
        $input = $this->input;

        $userId = $input['user']['id'] ?? 1;

        $page = empty($input['page']) ? 0 : $input['page'] - 1;
        $size = empty($input['size']) ? 10 : $input['size'];
        $where = ['user_id' => $userId];
        if (!empty($input['order_status'])) {
            $where['order_status'] = $input['order_status'];
        }
        $data = OrderModel::getList($where, ['id', 'client_name', 'create_time', 'order_status'], [$page * $size, $size]);

        return $this->responseSuccess('请求成功', $data);
    }


    public function orderDetail()
    {
        $input = $this->input;


        $userId = $input['user']['id'] ?? 1;


        $order = OrderModel::getOne(['user_id' => $userId, 'id' => $input['order_id']], ['client_name', 'client_address', 'client_realname', 'client_mobile', 'connect_status', 'detail', 'help_content', 'feedback']);

        if (!$order) return $this->responseError('订单不存在');

        return $this->responseSuccess('请求成功', $order);
    }
}